package com.gtmc.gclub.chat.jmessage;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.gtmc.gclub.chat.bean.Result;
import com.gtmc.gclub.chat.constants.ChatConstant;
import com.gtmc.gclub.chat.constants.CommonProperties;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jmessage.api.resource.DownloadResult;
import cn.jmessage.api.resource.ResourceClient;
import cn.jmessage.api.resource.UploadResult;

@Component(value = "resourceOperator")
@Scope
public class ResourceOperator {
	
	private  Logger log = LoggerFactory.getLogger(ResourceOperator.class);

	@Autowired
	private CommonProperties commonProperties;
	
    public  Result<Map> uploadFile(String fileName) {
    	log.debug("Jmessage uploadFile : " + fileName  );
        ResourceClient client = new ResourceClient(commonProperties.getAppkey(), commonProperties.getMasterSecret());
        Result<Map> rtn = null;
        try {
            UploadResult result = client.uploadFile(fileName);// "G:\\MyDownloads\\discourse-icon.png"
            log.debug(result.toString());
            log.debug("Update file. Res mediaId: " + result.getMediaId());
            
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("media_id", result.getMediaId());
            map.put("media_crc32", result.getMediaCrc32());
            map.put("width", result.getWidth());
            map.put("height", result.getHeight());
            map.put("format", result.getFormat());
            map.put("fsize", result.getFsize());
            
            rtn = new Result<Map>(1, map, null);

        } catch (APIConnectionException e) {
        	log.error("Connection error. Should retry later. ", e);
        	rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_CONNECTION, null, null);
        } catch (APIRequestException e) {
        	log.error("Error response from JPush server. Should review and fix it. ", e);
        	log.info("HTTP Status: " + e.getStatus());
        	log.info("Error Message: " + e.getMessage());
			JSONObject obj = new JSONObject(e.getMessage());
			JSONObject error = obj.optJSONObject("error");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", error.optInt("code"));
			map.put("message", error.optString("message"));
			rtn = new Result<Map>(0, map, String.valueOf(e.getStatus()));        	
        }
        return rtn;
    }	

    public  Result<Map> downloadFile(String mediaId) {
    	log.debug("Jmessage downloadFile : " + mediaId  );
        ResourceClient client = new ResourceClient(commonProperties.getAppkey(), commonProperties.getMasterSecret());
        Result<Map> rtn = null;
        
        try {
            DownloadResult result = client.downloadFile(mediaId);
            //String url = result.getUrl();
            
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("url", result.getUrl());
            rtn = new Result<Map>(1, map, null);
            
        } catch (APIConnectionException e) {
        	log.error("Connection error. Should retry later. ", e);
        	rtn = new Result<Map>(ChatConstant.RESULT_RETURN_FLAG_CONNECTION, null, null);
        } catch (APIRequestException e) {
        	log.error("Error response from JPush server. Should review and fix it. ", e);
        	log.info("HTTP Status: " + e.getStatus());
			JSONObject obj = new JSONObject(e.getMessage());
			JSONObject error = obj.optJSONObject("error");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", error.optInt("code"));
			map.put("message", error.optString("message"));
			rtn = new Result<Map>(0, map, String.valueOf(e.getStatus()));   
        }
        return rtn;
    }
}
